import { uploadUrl } from '../api/index'
import { website, tmplId } from '../api/config'
import { Base64 } from 'js-base64'
import { entryIsDispatchUrl } from './../api/individual'

// 图片正则
export const isImgRegexp = /\.(bmp|jpg|jpeg|png|webp|JPG|PNG|BMP|WEBP)$/
// 校验pdf文件正则
export const isPdfRegexp = /\.(pdf|PDF)$/

/**
 * 请求
 * @param {*} url 
 * @param {*} data 
 * @param {*} header 
 */
export const get = (url, data, header = {}) => {
  return request('GET', url, data, header)
}

/**
 * post请求
 * @param {*} url 
 * @param {*} data 
 * @param {*} header 
 * @param {*} isJSON 是否需要序列化
 */
export const post = (url = '', data, header = {}, isJSON = true) => {
  header['content-type'] = isJSON ? 'application/json' : 'application/x-www-form-urlencoded;charset=UTF-8'
  return request('POST', url, data, header)
}

/**
 * 封装微信请求方法
 * @param {*} method 
 * @param {*} url 
 * @param {*} data 
 * @param {*} header 
 */
const request = (method, url = '', data, header = {}) => {
  header.Authorization = `Basic ${Base64.encode(`${website.clientId}:${website.clientSecret}`)}`
  if (!url.endsWith('oauth/token')) {
    const token = wx.getStorageSync('token')
    header['Blade-Auth'] = `bearer ${token}`
  }
  return new Promise((resolve, reject) => {
    wx.showLoading({ title: '加载中', mask: true })
    wx.request({
      data,
      method,
      header,
      url,
      success: res => {
        wx.hideLoading()
        // 获取状态码
        const status = res.data.code || res.statusCode
        const message = res.data.msg || res.data.error_description || res.data.message || '未知错误'
        if (status === 200) {
          resolve(res.data)
        } else {
          if (status === 401) {
            wx.clearStorageSync()
            const url = getCurrentPage()
            if (url !== 'pages/login/login')
              wx.navigateTo({ url: '/pages/login/login' })
          }
          wx.showToast({ title: message, icon: 'none' })
          reject(res.data)
        }
      },
      fail: e => {
        wx.hideLoading()
        console.log(e)
      }
    })
  })
}

/**
 * 文件上传封装
 * @param {*} filePath 有赞上传空间传的路径
 * @param {*} header 请求头
 * @param {*} formData 其他参数
 */
export const uploadFile = (filePath, header = {}, formData = {}) => {
  header.Authorization = `Basic ${Base64.encode(`${website.clientId}:${website.clientSecret}`)}`
  const token = wx.getStorageSync('token')
  header['Blade-Auth'] = `bearer ${token}`
  return new Promise((resolve, reject) => {
    wx.showLoading({ title: '加载中' })
    wx.uploadFile({
      url: uploadUrl,
      filePath,
      header,
      name: 'file',
      formData,
      success: res => {
        wx.hideLoading()
        const resData = JSON.parse(res.data)
        const { code, data, msg } = resData
        if (code === 200) {
          resolve(resData)
          return
        }
        wx.showToast({ title: msg, icon: 'none' })
        reject(data)
      },
      fail: e => {
        wx.hideLoading()
        console.log(e)
      }
    })
  })
}

/**
 * 获取当前路由
 */
export const getCurrentPage = () => {
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  const url = `${currentPage.route}`
  return url
}

/**
 * 个人用户跳转页面逻辑
 * @param {Object} data 
 */
export const individualEntry = async data => {
  wx.setStorageSync('userStatus', data)
  if (!data.verified) { // 未实名去实名
    wx.navigateTo({ url: '/pages/individual/entry/verified/verified' })
    return
  }
  const companyId = wx.getStorageSync('companyId')
  const confirmId = wx.getStorageSync('confirmId')
  if (data.status === 3) { // 新员工已入职
    // 如果是旧系统拉取过来的数据，应该清空确认表信息
    if (companyId && confirmId) {
      wx.removeStorageSync('companyId')
      wx.removeStorageSync('confirmId')
      wx.showToast({
        title: '您目前是还在职，不能再次入职',
        icon: 'none',
        success: () => {
          setTimeout(() => {
            wx.navigateTo({ url: '/pages/individual/work/home/home' })
          }, 1000)
        }
      })
      return
    }
    wx.navigateTo({ url: '/pages/individual/work/home/home' })
    return
  }
  if (data.status === 4) { // 员工离职状态
    if (companyId && confirmId) {
      // 扫码进去跳完善信息
      wx.navigateTo({ url: '/pages/individual/entry/entry/entry?page=entry' })
      return
    }
    wx.navigateTo({ url: '/pages/individual/work/home/home' })
    return
  }
  if (data.status === 5) { // 员工其他状态不做跳转
    if (companyId && confirmId) {
      // 扫码进去跳完善信息
      wx.navigateTo({ url: '/pages/individual/entry/entry/entry?page=entry' })
      return
    }
    wx.showToast({ title: data.entryMsg, icon: 'none' })
    return
  }
  const { data: isDispath } = await post(entryIsDispatchUrl) // 查询旧系统是员工否已入职
  if (typeof isDispath === 'boolean') {
    wx.navigateTo({ url: '/pages/individual/work/home/home' })
    return
  }

  if (data.entryProcess === 1 || data.entryProcess === 2) { // 入职完善信息
    wx.navigateTo({ url: '/pages/individual/entry/entry/entry?page=entry' })
    return
  }
  if (data.entryProcess === 3 || data.entryProcess === 4) { // 入职状态
    wx.navigateTo({ url: '/pages/individual/entry/status/status' })
    return
  }
}

/**
 * 时间戳转时间显示
 *
 * @export
 * @param {*} date 时间new Date()格式
 *  * @param {*} fmt 转换时间格式 yyyy-MM-dd hh:mm:ss
 * @returns
 */
export const formatDate = (date, fmt) => { // 时间转化
  if (!date) return ''
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  let o = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds()
  }
  for (let k in o) {
    let str = o[k] + ''
    if (new RegExp(`(${k})`).test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str))
    }
  }
  return fmt
}

function padLeftZero (str) {
  return ('00' + str).substr(str.length)
}

/**
 * 校验是否是图片和pdf类型
 * @param {} type 
 */
export const isImgOrPDF = (type) => {
  return isImgRegexp.test(type) || isPdfRegexp.test(type)
}

/**
 * 构建upload控件fileList的数据
 * @param {Object} file 
 */
export const initUploadFileListKey = (file) => {
  file.name = file.fileName
  file.url = file.address ? file.address : file.link
  file.link = file.path ? file.path : file.link
  file.isImage = file.fileType !== 'pdf'
  return file
}

/**
 * 获取地址中query参数
 * @param {*} url 地址
 * @param {*} name 获取query中的name
 */
export const getQueryString = (url, name) => {
  const reg = new RegExp('(^|&|/?)' + name + '=([^&|/?]*)(&|/?|$)', 'i')
  const r = url.substr(1).match(reg)
  if (r != null) {
    return r[2]
  }
  return null
}

/**
 * 拉取用户获取订阅消息授权
 */
export const getMessageAuth = () => {
  wx.getSetting({
    withSubscriptions: true,
    success (res) {
      // 先判断用户是否有订阅了该消息
      const { itemSettings = {} } = res.subscriptionsSetting
      const resultMessage = itemSettings[tmplId] || ''
      if (resultMessage !== 'accept') {
        wx.requestSubscribeMessage({
          tmplIds: [tmplId],
          success (res) { }
        })
      }
    }
  })
}

/**
 * 是否是测试账号
 */
export const isTestAccount = () => {
  const user = wx.getStorageSync('user') || {}
  return user.user_name === '15905992320'
}

/**
 * 预览文件
 */
export const previewDocument = (url) => {
  wx.downloadFile({
    url,
    success: function (res) {
      const filePath = res.tempFilePath
      wx.openDocument({
        filePath: filePath
      })
    }
  })
}